package com.sskj.hhrt;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import sskj.lee.appupdatelibrary.BaseVersion;

public class NotifyDownloadService extends Service {
    private BaseVersion mBaseVersion;
    public boolean mCancelUpdata = false;
    private int NOTIFY_DOWNLOAD_ID = 1025;
    private NotificationManager mNotificationManager;
    private NotifyDownloadService.DownloadTask mDownloadTask;
    private Notification mNotification;
    private NotificationCompat.Builder mBuilder;

    public NotifyDownloadService() {
    }

    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        this.mDownloadTask = new NotifyDownloadService.DownloadTask();
        this.mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if (intent != null) {
            this.mBaseVersion = (BaseVersion) intent.getSerializableExtra(BaseUpdateDialogFragment.INTENT_KEY);
            if (mBaseVersion != null | intent != null) {
                showNotification();
            }
        }

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void onDestroy() {
        super.onDestroy();
        this.mNotificationManager.cancelAll();
        this.mDownloadTask.cancel(true);
    }

    private void showNotification() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel("channel_1", "channel_name_1", 4);
            this.mNotificationManager.createNotificationChannel(channel);
            this.mBuilder = new NotificationCompat.Builder(this.getApplicationContext(), "channel_1");
            this.mNotification = this.mBuilder.setSmallIcon(this.mBaseVersion.getNotifyIcon()).setOngoing(true).setContentIntent(this.getDefalutIntent(2)).setContentTitle("正在下载").setProgress(100, 0, false).build();
        } else {
            this.mBuilder = new NotificationCompat.Builder(this.getApplicationContext());
            this.mNotification = this.mBuilder.setSmallIcon(this.mBaseVersion.getNotifyIcon()).setLargeIcon(BitmapFactory.decodeResource(this.getResources(), this.mBaseVersion.getNotifyIcon())).setOngoing(true).setContentTitle("正在下载").setContentIntent(this.getDefalutIntent(2)).setProgress(100, 0, false).build();
        }

        this.mNotification.flags = 8;
        this.startForeground(this.NOTIFY_DOWNLOAD_ID, this.mNotification);
        this.mDownloadTask.execute(new String[]{this.mBaseVersion.getUrl()});
    }

    private PendingIntent getDefalutIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }

    class DownloadTask extends AsyncTask<String, Integer, File> {
        DownloadTask() {
        }

        protected File doInBackground(String... strings) {
            File apkFile = null;
            if (Environment.getExternalStorageState().equals("mounted")) {
                InputStream is = null;
                FileOutputStream fos = null;
                HttpURLConnection conn = null;

                try {
                    String savePath = String.format("%1$s/%2$s/download", Environment.getExternalStorageDirectory(), NotifyDownloadService.this.getPackageName());
                    URL url = new URL(NotifyDownloadService.this.mBaseVersion.getUrl());
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    long length = (long) conn.getContentLength();
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    apkFile = new File(savePath, TextUtils.isEmpty(NotifyDownloadService.this.mBaseVersion.getVersionName()) ? String.valueOf(System.currentTimeMillis() + ".apk") : NotifyDownloadService.this.mBaseVersion.getVersionName() + ".apk");
                    if (apkFile.exists()) {
                        apkFile.delete();
                    }

                    is = conn.getInputStream();
                    fos = new FileOutputStream(apkFile);
                    long count = 0L;
                    byte[] buf = new byte[1024];
                    int lastProgress = -1;

                    do {
                        int readNum = is.read(buf);
                        if (readNum <= 0) {
                            NotifyDownloadService.this.mCancelUpdata = true;
                            break;
                        }

                        count += (long) readNum;
                        fos.write(buf, 0, readNum);
                        int progress = (int) (count * 100L / length);
                        if (progress != lastProgress) {
                            lastProgress = progress;
                            NotifyDownloadService.this.mBuilder.setContentTitle("正在下载" + progress + "%");
                            NotifyDownloadService.this.mBuilder.setProgress(100, progress, false);
                            NotifyDownloadService.this.mNotification = NotifyDownloadService.this.mBuilder.build();
                            NotifyDownloadService.this.mNotification.flags = 8;
                            NotifyDownloadService.this.mNotificationManager.notify(NotifyDownloadService.this.NOTIFY_DOWNLOAD_ID, NotifyDownloadService.this.mNotification);
                            if (progress == 100) {
                                this.publishProgress(new Integer[]{(int) (count * 100L / length)});
                            }
                        }
                    } while (!NotifyDownloadService.this.mCancelUpdata);

                    fos.close();
                    is.close();
                } catch (MalformedURLException var27) {
                    var27.printStackTrace();
                } catch (IOException var28) {
                    var28.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }

                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException var26) {
                    }

                    if (conn != null) {
                        conn.disconnect();
                    }

                }
            } else {
                Toast.makeText(getApplicationContext(), "未检测到SD卡", Toast.LENGTH_SHORT).show();
            }

            return apkFile;
        }

        protected void onProgressUpdate(Integer... values) {
            mNotificationManager.cancel(NotifyDownloadService.this.NOTIFY_DOWNLOAD_ID);
        }

        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (file != null && file.exists()) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                if (Build.VERSION.SDK_INT >= 24) {
                    Uri contentUri = FileProvider.getUriForFile(NotifyDownloadService.this.getApplicationContext(), NotifyDownloadService.this.getPackageName() + ".fileProvider", file);
                    intent.putExtra("output", contentUri);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                }

                NotifyDownloadService.this.startActivity(intent);
            }

            NotifyDownloadService.this.mDownloadTask.cancel(true);
            NotifyDownloadService.this.stopSelf();
        }
    }
}
